package com.winit.commons.upush;

import com.alibaba.fastjson.JSONObject;
import com.winit.commons.util.HttpClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.util.StringUtils;

import java.util.Properties;

public class SendEmail {

    private static final Logger logger = LoggerFactory.getLogger(SendEmail.class);
    private static String UPUSH_URL = null;

    static {
        try {
            Properties properties = PropertiesLoaderUtils.loadAllProperties("application.properties");
            UPUSH_URL = properties.getProperty("upush_url");
        } catch (Exception e) {
            logger.error("初始化SendEmail异常。", e);
        }

    }

    /**
     * @param to      收件人邮箱
     * @param subject 邮件主题
     * @param body    邮件内容
     */
    public static void sendMail(String to, String subject, String body) {
        if (StringUtils.isEmpty(UPUSH_URL)) {
            logger.error("com.winit.common.util.MailUtil.sendMail UPUSH_URL为空");
            return;
        }
        JSONObject json = new JSONObject();
        json.put("to", to);
        json.put("subject", subject);
        json.put("body", getHtmlBody(body));
        try {
            HttpClientUtil.doPostForJson(UPUSH_URL, json.toJSONString());
        } catch (Exception e) {
            logger.error("com.winit.common.util.MailUtil.sendMail 异常", e);
        }
    }

    private static String getHtmlBody(String body) {
        String htmlBody = "<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"UTF-8\"><title>Title</title></head><body>"
                + body + "<br></body></html>";
        return htmlBody;
    }

    public static String getEmailAddr(String account) {
        return account + "@winit.com.cn";
    }

}
